﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.GHRMS.APP.AbsenceReportService;
using KPIS.GERP.SECURITY.BLL;
using System.Data;
using System.Globalization;
using KPIS.GERP.GHRMS.BLL;
using Telerik.Web.UI; 
using KPIS.GERP.GHRMS.APP.Classes;


namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class HRDEvaluation : System.Web.UI.Page
    {
        private UserBLL userBLL = new UserBLL();
        private SsMng ssMng = new SsMng();
        private HRDEvaluationBLL cmd = new HRDEvaluationBLL();
        private Main main = new Main();
        protected void Page_Load(object sender, EventArgs e)
        {
            if ( Convert.ToInt32(Request.QueryString["Re"]) == 1)
            {
                RadTabStrip1.FindTabByText("ผลการประเมิน").Selected = true;
                RadMultiPage1.FindPageViewByID("pgvRadResult").Selected = true;
            }

            if (!Page.IsPostBack)
            {
                GetUserInfo(ssMng.UserSeq);
                PageViewPerformanceAgreement();
                Round();
            }
        }

        public void AbsenceDetail(DateTime StartDate, DateTime EndDate)
        {
            PsAbsence[] HrmAbsence;
            RuleAbsence[] HrmAbsenceRule;
            string emp_seq = ssMng.EmpSeq;
            int intQuotaSick, intQuotaLeave, intQuotaHoliday, intQuotaLate, intQuotaOther = 0;
            double dblSick, dblLeave, dblHoliday, dblLate, dblOther = 0.0;

            //try
            //{
            using (var serviceClient = new AbsenceReportServiceClient())
            {
                //var name = serviceClient.Endpoint.Name;
                HrmAbsence = serviceClient.GetAbsenceDaysData(emp_seq);
                var Absence = (from l in HrmAbsence
                    where l.AbsenceTypeId == 1
                    where (l.StartDate >= StartDate) && (l.StartDate <= EndDate)
                    select l.DayCount).Sum(l => l.Value);
                dblSick = Convert.ToDouble(Absence);
                lblSick.Text = dblSick.ToString();

                Absence = (from l in HrmAbsence
                    where l.AbsenceTypeId == 3
                    where (l.StartDate >= StartDate) && (l.StartDate <= EndDate)
                    select l.DayCount).Sum(l => l.Value);
                dblLeave = Convert.ToDouble(Absence);
                lblLeave.Text = dblLeave.ToString();

                Absence = (from l in HrmAbsence
                    where l.AbsenceTypeId == 4
                    where (l.StartDate >= StartDate) && (l.StartDate <= EndDate)
                    select l.DayCount).Sum(l => l.Value);
                dblHoliday = Convert.ToDouble(Absence);
                lblHoliday.Text = dblHoliday.ToString();

                Absence = (from l in HrmAbsence
                    where l.AbsenceTypeId == 10
                    where (l.StartDate >= StartDate) && (l.StartDate <= EndDate)
                    select l.DayCount).Sum(l => l.Value);
                dblLate = Convert.ToDouble(Absence);
                lblLate.Text = dblLate.ToString();

                Absence = (from l in HrmAbsence
                    where l.AbsenceTypeId != 1 && l.AbsenceTypeId != 3 &&
                          l.AbsenceTypeId != 4 && l.AbsenceTypeId != 10
                    where (l.StartDate >= StartDate) && (l.StartDate <= EndDate)
                    select l.DayCount).Sum(l => l.Value);
                dblOther = Convert.ToDouble(Absence);
                lblOther.Text = dblOther.ToString();

                // Quota //
                HrmAbsenceRule = serviceClient.GetDaysLimitData(emp_seq);
                var Quota = (from l in HrmAbsenceRule
                    where l.AbsenceTypeId == 1
                    // ลาป่วย
                    select l.DayLimit).FirstOrDefault();
                intQuotaSick = Convert.ToInt32(Quota);
                lblLimitSick.Text = intQuotaSick.ToString("#");

                Quota = (from l in HrmAbsenceRule
                    where l.AbsenceTypeId == 3
                    // ลากิจ
                    select l.DayLimit).FirstOrDefault();
                intQuotaLeave = Convert.ToInt32(Quota);
                lblLimitLeave.Text = intQuotaLeave.ToString("#");

                Quota = (from l in HrmAbsenceRule
                    where l.AbsenceTypeId == 4
                    // ลาพักผ่อน
                    select l.DayLimit).FirstOrDefault();
                intQuotaHoliday = Convert.ToInt32(Quota);
                lblLimitHoliday.Text = intQuotaHoliday.ToString("#");

                Quota = (from l in HrmAbsenceRule
                    where l.AbsenceTypeId == 10
                    // มาสาย
                    select l.DayLimit).FirstOrDefault();
                intQuotaLate = Convert.ToInt32(Quota);
                lblLimitLate.Text = intQuotaLate.ToString("#");

                Quota = (from l in HrmAbsenceRule
                    where l.AbsenceTypeId != 1 && l.AbsenceTypeId != 3 &&
                          l.AbsenceTypeId != 4 && l.AbsenceTypeId != 10
                    select l.DayLimit).Sum();

                intQuotaOther = Convert.ToInt32(Quota);
                lblLimitOther.Text = intQuotaOther.ToString("#");

                int intSumQuota = intQuotaSick + intQuotaLeave + intQuotaHoliday + intQuotaLate + intQuotaOther;
                lblLimitSum.Text = intSumQuota.ToString();

                double dblSumAbsence = dblSick + dblLeave + dblHoliday + dblLate + dblOther;
                lblSum.Text = dblSumAbsence.ToString();
            }
            //}
            //catch (Exception ex)
            //{
            //    main.MessageAlert(Page, ex.Message.ToString());
            //}

        }

        public void Round()
        {
            int intEvalRoundSeq = Convert.ToInt32(Request.QueryString["EvalSeq"]);

            if (intEvalRoundSeq != 0)
            {
                DataTable dtRound = cmd.Round(intEvalRoundSeq);
                int intYear = Convert.ToInt32(dtRound.Rows[0]["round_year"]);
                lblRound.Text = dtRound.Rows[0]["round_and_year"].ToString();

                DateTime dateStartDate = Convert.ToDateTime(dtRound.Rows[0]["round_start_date"]);
                DateTime dateEndDate = Convert.ToDateTime(dtRound.Rows[0]["round_end_date"]);

                string strstartDate = dateStartDate.ToString("dd/MM/yyyy", new CultureInfo("th-TH"));
                string strendDate = dateEndDate.ToString("dd/MM/yyyy", new CultureInfo("th-TH"));

                pnlAbsent.GroupingText = "ข้อมูลการลา สรุปวันลาตั้งแต่วันที่ " + strstartDate + "   ถึงวันที่ " + strendDate;

                AbsenceDetail(dateStartDate, dateEndDate);

                DataTable dt = cmd.CheckOtherScore(Convert.ToInt32(ssMng.EmpSeq), intEvalRoundSeq);

                DataTable dtPosSeq = cmd.getPosSeq(Convert.ToInt32(ssMng.EmpSeq));
                int intPosSeq = Convert.ToInt32(dtPosSeq.Rows[0]["pos_seq"]);

                if (dt.Rows.Count > 0)
                {
                    btnSave.Visible = false;

                    DataRow[] drKPA = dt.Select(string.Format("table_ref = '{0}'", "hrm_perf_key_performance_area"), "");
                    DataRow[] drStrategy = dt.Select(string.Format("table_ref = '{0}'", "hrm_perf_job_assignment"), "");
                    DataRow[] drCoreCompetency = dt.Select(string.Format("table_ref = '{0}'", "hrm_perf_position_core_competency"), "");
                    DataRow[] drIDP = dt.Select(string.Format("table_ref = '{0}'", "hrm_perf_individual_dev_plan"), "");

                    DisibleRadioButtonListKPA(drKPA);
                    DisibleRadioButtonListStrategy(drStrategy);
                    DisibleRadioButtonListCoreCompetency(drCoreCompetency);
                    DisibleRadioButtonListIDP(drIDP);
                    
                    DataTable dtLoadResultIDP = cmd.LoadResultIDP(Convert.ToInt32(ssMng.EmpSeq), intEvalRoundSeq);
                    LoadResultIdp(dtLoadResultIDP);

                    rpt.DataSource = cmd.GetData();
                    rpt.DataBind(); 

                }
                else
                {
                    LoadGridKeyPerformanceArea(intPosSeq);
                    LoadGridCoreCompetency(intPosSeq);
                    LoadGridIDP(intPosSeq);
                    LoadGridStrategyProject(intYear, dateStartDate, dateEndDate);  //loadgridStrategy
                }
            }
            
        }
        
        public void GetUserInfo(string UserSequence)
        {
            DataSet ds = userBLL.LoadUser(Int32.Parse(UserSequence), (int?)null, (int?)null, "");

            if (ds != null)
            {

                DataTable dt = null;

                dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                    lblName.Text = dt.Rows[0]["USER_NAME"].ToString();
                    lblPosition.Text = dt.Rows[0]["POS_NAME"].ToString();
                    lblLevel.Text = dt.Rows[0]["CLASS_NAME"].ToString();
                    lblJobSite.Text = dt.Rows[0]["JOB_SITE_NAME"].ToString();

                    if (dt.Rows[0]["DATE_ADMITTED"].ToString() == "")
                    {
                        lblDateAdmit.Text = "";
                    }
                    else
                    {
                        lblDateAdmit.Text = Convert.ToDateTime(dt.Rows[0]["DATE_ADMITTED"].ToString()).ToString("d MMMM yyyy", new CultureInfo("th-TH"));

                    }

                    if (dt.Rows[0]["DATE_WORK_START"].ToString() == "")
                    {
                        lblDateWorkStart.Text = "";
                    }
                    else
                    {
                        lblDateWorkStart.Text = Convert.ToDateTime(dt.Rows[0]["DATE_WORK_START"].ToString()).ToString("d MMMM yyyy", new CultureInfo("th-TH"));

                    }
            }
        }

        public void PageViewPerformanceAgreement()
        {
            DataTable dt = cmd.LoadGoalObjective(Convert.ToInt32(ssMng.EmpSeq));
            grdRadDevelopmentNeed.DataSource = String.Empty;

            if (dt.Rows.Count > 0)
            {
                txtGoalObjective.Text = dt.Rows[0]["goal_objective"].ToString();
                txtRadActionPlan.Text = dt.Rows[0]["action_plan"].ToString();

                switch (main.ConvertNullInt(dt.Rows[0]["action_plan_score"]))
                {
                    case 5:
                    case 4:
                    case 3:
                    case 2:
                    case 1:
                        rblActionPlanScore.SelectedValue = Convert.ToString(dt.Rows[0]["action_plan_score"]);
                        break; 
                }

                switch (main.ConvertNullInt(dt.Rows[0]["action_plan_score_by_supervisor"]))
                {
                    case 5:
                    case 4:
                    case 3:
                    case 2:
                    case 1:
                        rblActionPlanScoreSupervisor.SelectedValue = Convert.ToString(dt.Rows[0]["action_plan_score_by_supervisor"]);
                        break;
                    default:
                        rblActionPlanScoreSupervisor.SelectedIndex = -1;
                        break;
                } 

                grdRadDevelopmentNeed.DataSource = cmd.LoadGridDevelopmentNeed(Convert.ToInt32(ssMng.EmpSeq));
                grdRadDevelopmentNeed.DataBind();
            }
        }

        public void LoadGridKeyPerformanceArea(int intPosSeq)
        {
            grdRadKPA.DataSource = cmd.LoadGridKPA(intPosSeq);
            grdRadKPA.DataBind();            
        }

        public void LoadGridCoreCompetency(int intPosSeq)
        {
            grdRadCoreCompetency.DataSource = cmd.LoadGridCoreCompetency(intPosSeq);
            grdRadCoreCompetency.DataBind();
        }

        public void LoadGridIDP(int intPosSeq)
        {
            grdRadIDP.DataSource = cmd.LoadGridIDP(intPosSeq);
            grdRadIDP.DataBind();
        }

        public void LoadGridStrategyProject(int intRoundYear, DateTime dateStartDate, DateTime dateEndDate)
        {
            grdRadStrategyProject.DataSource = cmd.LoadGridStrategyProject(intRoundYear, dateStartDate, dateEndDate, Convert.ToInt32(ssMng.EmpSeq));
            grdRadStrategyProject.DataBind();
        }

        protected void grdRadKPA_ItemDataBound(object sender, GridItemEventArgs e)
        {
            DataTable dtPosSeq = cmd.getPosSeq(Convert.ToInt32(ssMng.EmpSeq));
            int intPosSeq = Convert.ToInt32(dtPosSeq.Rows[0]["pos_seq"]);
           
            if (e.Item is GridDataItem)
            { 
                int intEvaluationListSeq = Convert.ToInt32(cmd.LoadGridKPA(intPosSeq).Rows[0]["evaluation_list_seq"]);

                GridDataItem item = e.Item as GridDataItem;
                RadioButtonList rblEmployeeScore = item.FindControl("rblEmployeeScore") as RadioButtonList;
                RadioButtonList rblSupervisorScore = item.FindControl("rblSupervisorScore") as RadioButtonList;
                HiddenField hdnFullScore = item.FindControl("hdnFullScore") as HiddenField;

                DataTable dtScore = cmd.LoadScoreFormat(intEvaluationListSeq);
                hdnFullScore.Value= dtScore.Compute("MAX(score_value)", "").ToString();  

                rblEmployeeScore.DataSource = dtScore;
                rblEmployeeScore.DataBind();

                rblSupervisorScore.DataSource = dtScore;
                rblSupervisorScore.DataBind();
            }          
            
        }

        protected void grdRadStrategyProject_ItemDataBound(object sender, GridItemEventArgs e)
        {
            int intEvalRoundSeq = Convert.ToInt32(Request.QueryString["EvalSeq"]);
            DataTable dtRound = cmd.Round(intEvalRoundSeq);
            int intYear = Convert.ToInt32(dtRound.Rows[0]["round_year"]);
            DateTime dateStartDate = Convert.ToDateTime(dtRound.Rows[0]["round_start_date"]);
            DateTime dateEndDate = Convert.ToDateTime(dtRound.Rows[0]["round_end_date"]);

            if (e.Item is GridDataItem)
            {
                DataTable dt = cmd.LoadGridStrategyProject(intYear, dateStartDate, dateEndDate, Convert.ToInt32(ssMng.EmpSeq));
                if ( dt.Rows.Count > 0 )
                {
                    int intEvaluationListSeq = Convert.ToInt32(dt.Rows[0]["evaluation_list_seq"]);

                    GridDataItem item = e.Item as GridDataItem;
                    RadioButtonList rblEmployeeScore = item.FindControl("rblEmployeeScore") as RadioButtonList;
                    RadioButtonList rblSupervisorScore = item.FindControl("rblSupervisorScore") as RadioButtonList;
                    HiddenField hdnFullScore = item.FindControl("hdnFullScore") as HiddenField;

                    DataTable dtScore = cmd.LoadScoreFormat(intEvaluationListSeq);
                    hdnFullScore.Value = dtScore.Compute("MAX(score_value)", "").ToString();

                    rblEmployeeScore.DataSource = dtScore;
                    rblEmployeeScore.DataBind();

                    rblSupervisorScore.DataSource = dtScore;
                    rblSupervisorScore.DataBind();
                }
            }
        }

        protected void grdRadCoreCompetency_ItemDataBound(object sender, GridItemEventArgs e)
        {
            DataTable dtPosSeq = cmd.getPosSeq(Convert.ToInt32(ssMng.EmpSeq));
            int intPosSeq = Convert.ToInt32(dtPosSeq.Rows[0]["pos_seq"]);

            if (e.Item is GridDataItem)
            {
                int intEvaluationListSeq = Convert.ToInt32(cmd.LoadGridCoreCompetency(intPosSeq).Rows[0]["evaluation_list_seq"]);

                GridDataItem item = e.Item as GridDataItem;
                RadioButtonList rblEmployeeScore = item.FindControl("rblEmployeeScore") as RadioButtonList;
                RadioButtonList rblSupervisorScore = item.FindControl("rblSupervisorScore") as RadioButtonList;
                HiddenField hdnFullScore = item.FindControl("hdnFullScore") as HiddenField;

                DataTable dtScore = cmd.LoadScoreFormat(intEvaluationListSeq);
                hdnFullScore.Value = dtScore.Compute("MAX(score_value)", "").ToString();

                rblEmployeeScore.DataSource = dtScore;
                rblEmployeeScore.DataBind();

                rblSupervisorScore.DataSource = dtScore;
                rblSupervisorScore.DataBind();
            }
        }

        protected void grdRadIDP_ItemDataBound(object sender, GridItemEventArgs e)
        {
            DataTable dtPosSeq = cmd.getPosSeq(Convert.ToInt32(ssMng.EmpSeq));
            int intPosSeq = Convert.ToInt32(dtPosSeq.Rows[0]["pos_seq"]);

            if (e.Item is GridDataItem)
            {
                int intEvaluationListSeq = Convert.ToInt32(cmd.LoadGridIDP(intPosSeq).Rows[0]["evaluation_list_seq"]);

                GridDataItem item = e.Item as GridDataItem;
                RadioButtonList rblEmployeeScore = item.FindControl("rblEmployeeScore") as RadioButtonList;
                RadioButtonList rblSupervisorScore = item.FindControl("rblSupervisorScore") as RadioButtonList;
                HiddenField hdnFullScore = item.FindControl("hdnFullScore") as HiddenField;

                DataTable dtScore = cmd.LoadScoreFormat(intEvaluationListSeq);
                hdnFullScore.Value = dtScore.Compute("MAX(score_value)", "").ToString();

                rblEmployeeScore.DataSource = dtScore;
                rblEmployeeScore.DataBind();

                rblSupervisorScore.DataSource = dtScore;
                rblSupervisorScore.DataBind();
            }
        }

        protected void grdRadResultIDP_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem item = e.Item as GridDataItem;

                RadComboBox cboDevMethod = (RadComboBox)item.FindControl("cboRadDevMethod");

                cboDevMethod.DataSource = cmd.LoadDevelopmentMethod();
                cboDevMethod.DataBind();
                cboDevMethod.Items.Insert(0, new RadComboBoxItem("--- เลือกวิธีการพัฒนา ---", ""));
            }

        }

        protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            int intEvalRoundSeq = Convert.ToInt32(Request.QueryString["EvalSeq"]);

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                RadGrid rg = (RadGrid)e.Item.FindControl("grdRadResult");
                if (rg != null)
                {
                    DataRowView drv = (DataRowView)e.Item.DataItem;
                    rg.DataSource = cmd.GetSubData(Convert.ToInt32(drv["weight_header_seq"]), Convert.ToInt32(ssMng.EmpSeq), intEvalRoundSeq);
                    rg.DataBind();
                }
            }
        }

        protected void DisibleControl()
        {
            txtRadRemarkKPA.ReadOnly = true;
            txtRadRemarkStrategy.ReadOnly = true;
            txtRadRemarkCoreCompetency.ReadOnly = true;
            txtRadRemarkIDP.ReadOnly = true;

            foreach (GridDataItem item in grdRadKPA.MasterTableView.Items)
            {
                RadioButtonList rblScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                RadTextBox txtComment = (RadTextBox)item.FindControl("txtEmployeeComment");
                rblScore.Enabled = false;
                txtComment.Enabled = false;
            }

            foreach (GridDataItem item in grdRadStrategyProject.MasterTableView.Items)
            {
                RadioButtonList rblScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                RadTextBox txtComment = (RadTextBox)item.FindControl("txtEmployeeComment");
                rblScore.Enabled = false;
                txtComment.Enabled = false;
            }

            foreach (GridDataItem item in grdRadCoreCompetency.MasterTableView.Items)
            {
                RadioButtonList rblScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                RadTextBox txtComment = (RadTextBox)item.FindControl("txtEmployeeComment");
                rblScore.Enabled = false;
                txtComment.Enabled = false;
            }

            foreach (GridDataItem item in grdRadIDP.MasterTableView.Items)
            {
                RadioButtonList rblScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                RadTextBox txtComment = (RadTextBox)item.FindControl("txtEmployeeComment");
                rblScore.Enabled = false;
                txtComment.Enabled = false;
            }          
                
        }

        protected void btnSave_Clicked(object sender, EventArgs e)
        {            
            DataTable dtList = cmd.LoadEvaluationList();

            //try
            //{
                DataSet dsKPA = ScoreKPA(dtList);   
                DataSet dsStrategy = ScoreStrategyProject(dtList);  
                DataSet dsCC = ScoreCoreCompetency(dtList); 
                DataSet dsIDP = ScoreIDP(dtList);   
                string str = cmd.SaveEvaluationScore(dsKPA, dsStrategy, dsCC, dsIDP);

                var strParam = Request.QueryString["EvalSeq"];
                Response.Redirect(string.Format("HRDEvaluation.aspx?EvalSeq={0}&Re=1", strParam));
            //}
            //catch (Exception ex)
            //{
            //    Session["error"] = Convert.ToString(Session["error"]) + ex.Message;
            //}
           
            //finally
            //{
               
            //}
                
        }

        protected DataSet ScoreKPA(DataTable dtEvalutionList) 
        {             
            DataRow[] rowList = dtEvalutionList.Select(string.Format("table_ref = '{0}'", "hrm_perf_key_performance_area"), "");
            int? intListId = null;
            if (rowList.Length > 0)
            {
                intListId = (int)rowList[0]["evaluation_list_seq"];
            }
            
            Double dblEmpGrandTotalWeight = 0.0;
            Double dblEmpTotalScore = 0.0;
            Double dblTotalMaxValue = 0.0;
            Double dblEmpTotal = 0.0;
            bool isWeight = false;

            DataTable dtHeader = cmd.GetHeaderSchema();
            DataTable dtDetail = cmd.GetDetailSchema();

            dtHeader.TableName = "Header";
            dtDetail.TableName = "Detail";
        
            foreach (GridDataItem item in grdRadKPA.MasterTableView.Items)
            {
                int intFullScore = Convert.ToInt32(item["full_score"].Text == "&nbsp;" ? "0" : item["full_score"].Text);

                isWeight = Convert.ToBoolean(Convert.ToInt32(item["isdetailweight"].Text == "&nbsp;" ? "0" : item["isdetailweight"].Text));

                RadTextBox txtComment = (RadTextBox)item.FindControl("txtEmployeeComment");
                RadioButtonList rblScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                int intScore = 0;
                if (rblScore != null)
                {
                    intScore = Convert.ToInt32(rblScore.SelectedValue);
                }

                string strComment = "";
                if (txtComment != null)
                {
                    strComment = txtComment.Text;
                }

                if (isWeight)
                {
                    int intWeight = Convert.ToInt32(item["weight"].Text);
                    dblEmpTotal = (intScore * intWeight) / intFullScore;
                    dblEmpGrandTotalWeight += dblEmpTotal;
                }
                else
                {
                    dblEmpTotalScore += intScore;
                    dblTotalMaxValue += intFullScore;
                    dblEmpGrandTotalWeight = (dblEmpTotalScore / dblTotalMaxValue) * 100.0;
                
                }

                DataRow drow = dtDetail.NewRow();
                drow["evaluation_seq"] = DBNull.Value;
                drow["detail_entity_seq"] = item.GetDataKeyValue("kpa_seq");
                drow["detail_description"] = item["key_area_name"].Text;
                drow["long_description"] = item["description"].Text;
                drow["weight"] = Convert.ToInt32(item["weight"].Text);
                drow["full_score"] = intFullScore;
                drow["employee_score"] = intScore;
                drow["employee_comment"] = strComment;
                drow["created_by"] = ssMng.EmpSeq;
                drow["created_when"] = DateTime.Now;
                drow["record_status"] = "U";
                dtDetail.Rows.Add(drow);
            }

            DataRow rowH = dtHeader.NewRow();
            rowH["emp_seq"] = ssMng.EmpSeq;
            rowH["evaluation_list_seq"] = intListId;
            rowH["evaluation_date"] = DateTime.Now;
            rowH["evaluation_round_seq"] = Convert.ToInt32(Request.QueryString["EvalSeq"]);
            rowH["employee_total_score"] = Double.IsInfinity(dblEmpGrandTotalWeight) ? 0 : dblEmpGrandTotalWeight;
            rowH["created_by"] = ssMng.EmpSeq;
            rowH["created_when"] = DateTime.Now;
            rowH["record_status"] = "U";
            rowH["remark"] = txtRadRemarkKPA.Text;
            dtHeader.Rows.Add(rowH);

            DataSet ds = new DataSet();
            ds.Tables.Add(dtHeader.Copy());
            ds.Tables.Add(dtDetail.Copy());

            return ds;

          
        }

        protected DataSet ScoreStrategyProject(DataTable dtEvalutionList)   
        {           
            DataRow[] rowList = dtEvalutionList.Select(string.Format("table_ref = '{0}'", "hrm_perf_job_assignment"), "");
            int? intListId = null;
            if (rowList.Length > 0)
            {
                intListId = (int)rowList[0]["evaluation_list_seq"];
            }

            Double dblEmpGrandTotalWeight = 0.0;
            Double dblEmpTotalScore = 0.0;
            Double dblTotalMaxValue = 0.0;
            Double dblEmpTotal = 0.0;
            bool isWeight = false;

            DataTable dtHeader = cmd.GetHeaderSchema();
            DataTable dtDetail = cmd.GetDetailSchema();

            dtHeader.TableName = "Header";
            dtDetail.TableName = "Detail";

            foreach (GridDataItem item in grdRadStrategyProject.MasterTableView.Items)
            {

                int intFullScore = Convert.ToInt32(item["full_score"].Text);
                
                isWeight = Convert.ToBoolean(Convert.ToInt32(item["isdetailweight"].Text));

                RadTextBox txtComment = (RadTextBox)item.FindControl("txtEmployeeComment");
                RadioButtonList rblScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                int intScore = 0;
                if (rblScore != null)
                {
                    intScore = Convert.ToInt32(rblScore.SelectedValue);
                }

                string strComment = "";
                if (txtComment != null)
                {
                    strComment = txtComment.Text;
                }

                if (isWeight)
                {
                    int intWeight = Convert.ToInt32(item["weight"].Text);
                    dblEmpTotal = (intScore * intWeight) / intFullScore;
                    dblEmpGrandTotalWeight += dblEmpTotal;
                }
                else
                {
                    dblEmpTotalScore += intScore;
                    dblTotalMaxValue += intFullScore;
                    dblEmpGrandTotalWeight = (dblEmpTotalScore / dblTotalMaxValue) * 100.0;

                }

                DataRow drow = dtDetail.NewRow();
                drow["evaluation_seq"] = DBNull.Value; ;
                drow["detail_entity_seq"] = item.GetDataKeyValue("bgm_proj_job_assign_seq");
                drow["detail_description"] = item["bgm_proj_name"].Text;
                drow["long_description"] = item["job_title"].Text;
                drow["full_score"] = item["full_score"].Text;
                drow["employee_score"] = intScore;
                drow["employee_comment"] = strComment;
                drow["created_by"] = ssMng.EmpSeq;
                drow["created_when"] = DateTime.Now;
                drow["record_status"] = "U";
                dtDetail.Rows.Add(drow);
            }

            DataRow rowH = dtHeader.NewRow();
            rowH["emp_seq"] = ssMng.EmpSeq;
            rowH["evaluation_list_seq"] = intListId;
            rowH["evaluation_date"] = DateTime.Now;
            rowH["evaluation_round_seq"] = Convert.ToInt32(Request.QueryString["EvalSeq"]);
            rowH["employee_total_score"] = dblEmpGrandTotalWeight;
            rowH["created_by"] = ssMng.EmpSeq;
            rowH["created_when"] = DateTime.Now;
            rowH["record_status"] = "U";
            rowH["remark"] = txtRadRemarkStrategy.Text;
            dtHeader.Rows.Add(rowH);

            DataSet ds = new DataSet();
            ds.Tables.Add(dtHeader.Copy());
            ds.Tables.Add(dtDetail.Copy());

            return ds;

        }

        protected DataSet ScoreCoreCompetency(DataTable dtEvalutionList)
        {
            DataTable dtGetExpectResult = cmd.GetExpectResult(Convert.ToInt32(ssMng.EmpSeq));
            
            DataRow[] rowList = dtEvalutionList.Select(string.Format("table_ref = '{0}'", "hrm_perf_position_core_competency"), "");
            int? intListId = null;
            if (rowList.Length > 0)
            {
                intListId = (int)rowList[0]["evaluation_list_seq"];
            }

            Double dblEmpGrandTotalWeight = 0.0;
            Double dblEmpTotalScore = 0.0;
            Double dblTotalMaxValue = 0.0;
            Double dblEmpTotal = 0.0;
            bool isWeight = false;

            DataTable dtHeader = cmd.GetHeaderSchema();
            DataTable dtDetail = cmd.GetDetailSchema();

            dtHeader.TableName = "Header";
            dtDetail.TableName = "Detail";

            foreach (GridDataItem item in grdRadCoreCompetency.MasterTableView.Items)
            {
                RadTextBox txtComment = (RadTextBox)item.FindControl("txtEmployeeComment");
                RadioButtonList rblScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                HiddenField hdfExpectScore = (HiddenField)item.FindControl("hdnFullScore");

                int intFullScore = Convert.ToInt32(item["full_score"].Text == "&nbsp;" ? "0" : item["full_score"].Text);

                isWeight = Convert.ToBoolean(Convert.ToInt32(item["isdetailweight"].Text == "&nbsp;" ? "0" : item["isdetailweight"].Text));

                int intEntityID = Convert.ToInt32(item.GetDataKeyValue("pos_competency_seq"));

                DataRow[] drExpect = dtGetExpectResult.Select(string.Format("pos_competency_seq = {0}", intEntityID), "");
                if (drExpect.Length > 0)
                {
                    foreach (var row in drExpect)
                    {
                        hdfExpectScore.Value = row["expect_result"].ToString();
                    }
                }

                int intScore = 0;
                int intSupInScore = 0;
                int intExpectScore = Convert.ToInt32(hdfExpectScore.Value);

                if (rblScore != null)
                {
                    intScore = Convert.ToInt32(rblScore.SelectedValue);
                }

                string strComment = "";
                if (txtComment != null)
                {
                    strComment = txtComment.Text;
                }

                if (intExpectScore == 5)
                {
                    intSupInScore = (intScore - intExpectScore) + 5;
                }
                else
                {
                    intSupInScore = (intScore - intExpectScore) + 4;

                    if (intSupInScore > 5)
                    {
                        intSupInScore = 5;
                    }
                }

                if (isWeight)
                {
                    int intWeight = Convert.ToInt32(item["weight"].Text == "&nbsp;" ? "0" : item["weight"].Text);
                    dblEmpTotal = (intSupInScore * intWeight) / intFullScore;
                    dblEmpGrandTotalWeight += dblEmpTotal;
                }
                else
                {
                    dblEmpTotalScore += intSupInScore;
                    dblTotalMaxValue += intFullScore;
                    dblEmpGrandTotalWeight = (dblEmpTotalScore / dblTotalMaxValue) * 100.0;

                }
                  
                DataRow drow = dtDetail.NewRow();
                drow["evaluation_seq"] = DBNull.Value;
                drow["detail_entity_seq"] = intEntityID;
                drow["detail_description"] = item["core_competency_name"].Text;
                drow["long_description"] = item["level_name"].Text;
                drow["weight"] = item["weight"].Text;
                drow["full_score"] = item["full_score"].Text == "&nbsp;" ? "0" : item["full_score"].Text;
                drow["employee_score"] = intScore;
                drow["employee_comment"] = strComment;
                drow["created_by"] = ssMng.EmpSeq;
                drow["created_when"] = DateTime.Now;
                drow["record_status"] = "U";
                dtDetail.Rows.Add(drow);
            }

            DataRow rowH = dtHeader.NewRow();
            rowH["emp_seq"] = ssMng.EmpSeq;
            rowH["evaluation_list_seq"] = intListId;
            rowH["evaluation_date"] = DateTime.Now;
            rowH["evaluation_round_seq"] = Convert.ToInt32(Request.QueryString["EvalSeq"]);
            rowH["employee_total_score"] = double.IsPositiveInfinity(dblEmpGrandTotalWeight) ? 0 : dblEmpGrandTotalWeight;
            rowH["created_by"] = ssMng.EmpSeq;
            rowH["created_when"] = DateTime.Now;
            rowH["record_status"] = "U";
            rowH["remark"] = txtRadRemarkCoreCompetency.Text;
            dtHeader.Rows.Add(rowH);
            DataSet ds = new DataSet();
            ds.Tables.Add(dtHeader.Copy());
            ds.Tables.Add(dtDetail.Copy());

            return ds;
        }

        protected DataSet ScoreIDP(DataTable dtEvalutionList)  
        {
            
            DataRow[] rowList = dtEvalutionList.Select(string.Format("table_ref = '{0}'", "hrm_perf_individual_dev_plan"), "");
            int? intListId = null;
            if (rowList.Length > 0)
            {
                intListId = (int)rowList[0]["evaluation_list_seq"];
            }

            Double dblEmpGrandTotalWeight = 0.0;
            Double dblEmpTotalScore = 0.0;
            Double dblTotalMaxValue = 0.0;
            Double dblEmpTotal = 0.0;
            bool isWeight = false;

            DataTable dtHeader = cmd.GetHeaderSchema();
            DataTable dtDetail = cmd.GetDetailSchema();

            dtHeader.TableName = "Header";
            dtDetail.TableName = "Detail";

            foreach (GridDataItem item in grdRadIDP.MasterTableView.Items)
            {
                int intFullScore = Convert.ToInt32(item["full_score"].Text == "&nbsp;" ? "0" : item["full_score"].Text);

                isWeight = Convert.ToBoolean(Convert.ToInt32(item["isdetailweight"].Text == "&nbsp;" ? "0" : item["isdetailweight"].Text));

                RadTextBox txtComment = (RadTextBox)item.FindControl("txtEmployeeComment");
                RadioButtonList rblScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                int intScore = 0;
                if (rblScore != null)
                {
                    intScore = Convert.ToInt32(rblScore.SelectedValue);
                }

                string strComment = "";
                if (txtComment != null)
                {
                    strComment = txtComment.Text;
                }

                if (isWeight)
                {
                    int intWeight = Convert.ToInt32(item["weight"].Text == "&nbsp;" ? "0" : item["weight"].Text);
                    dblEmpTotal = (intScore * intWeight) / intFullScore;
                    dblEmpGrandTotalWeight += dblEmpTotal;
                }
                else
                {
                    dblEmpTotalScore += intScore;
                    dblTotalMaxValue += intFullScore;
                    dblEmpGrandTotalWeight = (dblEmpTotalScore / dblTotalMaxValue) * 100.0;

                }

                DataRow drow = dtDetail.NewRow();
                drow["evaluation_seq"] = DBNull.Value;
                drow["detail_entity_seq"] = item.GetDataKeyValue("idp_seq");
                drow["detail_description"] = HttpUtility.HtmlDecode(item["type_name"].Text);
                drow["long_description"] = HttpUtility.HtmlDecode(item["description"].Text);
                drow["full_score"] = string.IsNullOrEmpty((HttpUtility.HtmlDecode(item["full_score"].Text) ?? "").Trim()) ? 0 : Convert.ToInt32((HttpUtility.HtmlDecode(item["full_score"].Text) ?? "").Trim());
                drow["employee_score"] = intScore;
                drow["employee_comment"] = strComment;
                drow["created_by"] = ssMng.EmpSeq;
                drow["created_when"] = DateTime.Now;
                drow["record_status"] = "U";
                dtDetail.Rows.Add(drow);
            }

            DataRow rowH = dtHeader.NewRow();
            rowH["emp_seq"] = ssMng.EmpSeq;
            rowH["evaluation_list_seq"] = intListId;
            rowH["evaluation_date"] = DateTime.Now;
            rowH["evaluation_round_seq"] = Convert.ToInt32(Request.QueryString["EvalSeq"]);
            rowH["employee_total_score"] = Double.IsInfinity(dblEmpGrandTotalWeight) ? 0 : dblEmpGrandTotalWeight;
            rowH["created_by"] = ssMng.EmpSeq;
            rowH["created_when"] = DateTime.Now;
            rowH["record_status"] = "U";
            rowH["remark"] = txtRadRemarkIDP.Text;
            dtHeader.Rows.Add(rowH);

            DataSet ds = new DataSet();
            ds.Tables.Add(dtHeader.Copy());
            ds.Tables.Add(dtDetail.Copy());

            return ds;
        }

        protected void DisibleRadioButtonListKPA(DataRow[] dr)
        {
            string[] key = { "evaluation_detail_seq" };
            grdRadKPA.MasterTableView.DataKeyNames = key;
            grdRadKPA.DataSource = dr;
            grdRadKPA.DataBind();

            txtRadRemarkKPA.ReadOnly = true;
            
            List<DataRow> list = dr.AsEnumerable().ToList();

            foreach (GridDataItem item in grdRadKPA.MasterTableView.Items)
            {
                RadioButtonList rblSupScore = (RadioButtonList)item.FindControl("rblSupervisorScore");
                RadTextBox txtSupComment = (RadTextBox)item.FindControl("txtSupervisorComment");
                RadioButtonList rblEmpScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                RadTextBox txtEmpComment = (RadTextBox)item.FindControl("txtEmployeeComment");

                rblEmpScore.Enabled = false;
                txtEmpComment.Enabled = false;
                rblSupScore.Enabled = false;
                txtSupComment.Enabled = false;

                item["key_area_name"].Text = list[item.ItemIndex]["detail_description"].ToString();
                item["description"].Text = list[item.ItemIndex]["long_description"].ToString();
                
                //ลูกน้อง
                txtRadRemarkKPA.Text = list[item.ItemIndex]["remark"].ToString();
                txtEmpComment.Text = list[item.ItemIndex]["employee_comment"].ToString();               
                rblEmpScore.SelectedValue = list[item.ItemIndex]["employee_score"].ToString();

                //หัวหน้า
                txtSupComment.Text = list[item.ItemIndex]["other_comment"].ToString();
                rblSupScore.SelectedValue = list[item.ItemIndex]["other_score"].ToString();
                   
                GridFooterItem footerItem = (GridFooterItem)grdRadKPA.MasterTableView.GetItems(GridItemType.Footer)[0];
                Label lblEmpGrandTotal = (Label)footerItem.FindControl("lblFooterTotalScore");
                Label lblSupGrandTotal = (Label)footerItem.FindControl("lblFooterKPASupTotalScore");
                lblEmpGrandTotal.Text = list[item.ItemIndex]["employee_total_score"].ToString();
                lblSupGrandTotal.Text = list[item.ItemIndex]["supervisor_total_score"].ToString();
            }
        }

        protected void DisibleRadioButtonListStrategy(DataRow[] dr)
        {
            string[] key = { "evaluation_detail_seq" };
            grdRadStrategyProject.MasterTableView.DataKeyNames = key;
            grdRadStrategyProject.DataSource = dr;
            grdRadStrategyProject.DataBind();

            txtRadRemarkStrategy.ReadOnly = true;

            List<DataRow> list = dr.AsEnumerable().ToList();
           
            foreach (GridDataItem item in grdRadStrategyProject.MasterTableView.Items)
            {
                RadioButtonList rblSupScore = (RadioButtonList)item.FindControl("rblSupervisorScore");
                RadTextBox txtSupComment = (RadTextBox)item.FindControl("txtSupervisorComment");
                RadioButtonList rblEmpScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                RadTextBox txtEmpComment = (RadTextBox)item.FindControl("txtEmployeeComment");

                rblEmpScore.Enabled = false;
                txtEmpComment.Enabled = false;

                item["bgm_proj_name"].Text = list[item.ItemIndex]["detail_description"].ToString();
                item["job_title"].Text = list[item.ItemIndex]["long_description"].ToString();


                //ลูกน้อง
                txtRadRemarkStrategy.Text = list[item.ItemIndex]["remark"].ToString();
                txtEmpComment.Text = list[item.ItemIndex]["employee_comment"].ToString();    
                rblEmpScore.SelectedValue = list[item.ItemIndex]["employee_score"].ToString();

                //หัวหน้า
                txtSupComment.Text = list[item.ItemIndex]["other_comment"].ToString();
                rblSupScore.SelectedValue = list[item.ItemIndex]["other_score"].ToString();

                GridFooterItem footerItem = (GridFooterItem)grdRadStrategyProject.MasterTableView.GetItems(GridItemType.Footer)[0];
                Label lblEmpGrandStrategyTotal = (Label)footerItem.FindControl("lblFooterStrategyTotalScore");
                Label lblSupGrandStrategyTotal = (Label)footerItem.FindControl("lblFooterStrategySupTotalScore");
                lblEmpGrandStrategyTotal.Text = list[item.ItemIndex]["employee_total_score"].ToString();
                lblSupGrandStrategyTotal.Text = list[item.ItemIndex]["supervisor_total_score"].ToString();                    
            }
            
        }

        protected void DisibleRadioButtonListCoreCompetency(DataRow[] dr)
        {
            string[] key = { "evaluation_detail_seq" };
            grdRadCoreCompetency.MasterTableView.DataKeyNames = key;
            grdRadCoreCompetency.DataSource = dr;
            grdRadCoreCompetency.DataBind();

            txtRadRemarkCoreCompetency.ReadOnly = true;

            List<DataRow> list = dr.AsEnumerable().ToList();

            foreach (GridDataItem item in grdRadCoreCompetency.MasterTableView.Items)
            {
                RadioButtonList rblSupScore = (RadioButtonList)item.FindControl("rblSupervisorScore");
                RadTextBox txtSupComment = (RadTextBox)item.FindControl("txtSupervisorComment");
                RadioButtonList rblEmpScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                RadTextBox txtEmpComment = (RadTextBox)item.FindControl("txtEmployeeComment");

                rblEmpScore.Enabled = false;
                txtEmpComment.Enabled = false;

                item["core_competency_name"].Text = list[item.ItemIndex]["detail_description"].ToString();
                item["level_name"].Text = list[item.ItemIndex]["long_description"].ToString();

                //ลูกน้อง
                txtRadRemarkCoreCompetency.Text = list[item.ItemIndex]["remark"].ToString();
                txtEmpComment.Text = list[item.ItemIndex]["employee_comment"].ToString();
                rblEmpScore.SelectedValue = list[item.ItemIndex]["employee_score"].ToString();

                //หัวหน้า
                txtSupComment.Text = list[item.ItemIndex]["other_comment"].ToString();
                rblSupScore.SelectedValue = list[item.ItemIndex]["other_score"].ToString();
                   

                GridFooterItem footerItem = (GridFooterItem)grdRadCoreCompetency.MasterTableView.GetItems(GridItemType.Footer)[0];
                Label lblEmpGrandCoreCompetencyTotal = (Label)footerItem.FindControl("lblFooterCoreCompetencyTotalScore");
                Label lblSupGrandCoreCompetencyTotal = (Label)footerItem.FindControl("lblFooterCoreCompetencySupTotalScore");

                lblEmpGrandCoreCompetencyTotal.Text = list[item.ItemIndex]["employee_total_score"].ToString();
                lblSupGrandCoreCompetencyTotal.Text = list[item.ItemIndex]["supervisor_total_score"].ToString();
            }
        }

        protected void DisibleRadioButtonListIDP(DataRow[] dr)
        {
            string[] key = { "evaluation_detail_seq" };
            grdRadIDP.MasterTableView.DataKeyNames = key;
            grdRadIDP.DataSource = dr;
            grdRadIDP.DataBind();

            txtRadRemarkIDP.ReadOnly = true;

            List<DataRow> list = dr.AsEnumerable().ToList();
           
            foreach (GridDataItem item in grdRadIDP.MasterTableView.Items)
            {
                RadioButtonList rblSupScore = (RadioButtonList)item.FindControl("rblSupervisorScore");
                RadTextBox txtSupComment = (RadTextBox)item.FindControl("txtSupervisorComment");
                RadioButtonList rblEmpScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                RadTextBox txtEmpComment = (RadTextBox)item.FindControl("txtEmployeeComment");

                rblEmpScore.Enabled = false;
                txtEmpComment.Enabled = false;

                item["type_name"].Text = list[item.ItemIndex]["detail_description"].ToString();
                item["proficiency_name"].Text = list[item.ItemIndex]["long_description"].ToString();

                int intFullScore = Convert.ToInt32(list[item.ItemIndex]["full_score"]);

                //ลูกน้อง
                txtRadRemarkIDP.Text = list[item.ItemIndex]["remark"].ToString();
                txtEmpComment.Text = list[item.ItemIndex]["employee_comment"].ToString();                
                rblEmpScore.SelectedValue = list[item.ItemIndex]["employee_score"].ToString();

                //หัวหน้า
                txtSupComment.Text = list[item.ItemIndex]["other_comment"].ToString();
                rblSupScore.SelectedValue = list[item.ItemIndex]["other_score"].ToString();
            }

        }

        protected void LoadResultIdp(DataTable dt)
        {
            grdRadResultIDP.DataSource = dt;
            grdRadResultIDP.DataBind();

            List<DataRow> list = dt.AsEnumerable().ToList();

            foreach (GridDataItem item in grdRadResultIDP.MasterTableView.Items)
            {
                RadComboBox cboDevMethod = (RadComboBox)item.FindControl("cboRadDevMethod");
                RadioButtonList rblPriority = (RadioButtonList)item.FindControl("rblPriority");
                RadioButtonList rblQuarter = (RadioButtonList)item.FindControl("rblQuarter");
                RadTextBox txtReason = (RadTextBox)item.FindControl("txtReason");

                int intDetailSeq = Convert.ToInt32(item.GetDataKeyValue("evaluation_detail_seq"));

                cboDevMethod.SelectedValue = list[item.ItemIndex]["dev_method_seq"].ToString();
                rblPriority.SelectedValue = list[item.ItemIndex]["priority"].ToString();
                rblQuarter.SelectedValue = list[item.ItemIndex]["period"].ToString();
                txtReason.Text = list[item.ItemIndex]["remark"].ToString();
            }
        }
    }
}